package pl.matt.dao.impl;

import java.util.Collection;

import org.apache.commons.collections.CollectionUtils;

import pl.matt.dao.FrameRegionDao;
import pl.matt.model.Frame;
import pl.matt.model.FrameRegion;
import pl.matt.model.FrameRegionType;
import pl.matt.model.Video;

public class HibernateFrameRegionDao extends HibernateAbstractEntityDao<FrameRegion> implements FrameRegionDao {

	//@SuppressWarnings("unused")
	private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(HibernateFrameRegionDao.class);
	
	protected HibernateFrameRegionDao() {
		super(FrameRegion.class);
	}

	@Override
	public int deleteByVideo(Video video) {
		String hql = "DELETE FROM " + getEntityClass().getName() + " e WHERE e.frame IN (SELECT f FROM Frame f WHERE f.video = ?)";
		LOG.debug(hql + " <-- hql");
		return getHibernateTemplate().bulkUpdate(hql, video);
	}

	@Override
	public int deleteByVideoNameAndFrameRegionType(String videoName, FrameRegionType frameRegionType) {
		String hql = "DELETE FROM " + getEntityClass().getName() + " e WHERE e.frame.id IN " +
				"(SELECT f.id FROM Frame f WHERE f.video.name = ?) AND e.frameRegionType = ?";
		LOG.debug(hql + " <-- hql");
		return getHibernateTemplate().bulkUpdate(hql, new Object[] {videoName, frameRegionType});
	}

	@SuppressWarnings("unchecked")
	@Override
	public FrameRegion findVerifiedByFrameAndFrameRegionType(Frame frame, FrameRegionType frameRegionType) {
		String hql = "FROM " + getEntityClass().getName() + " r WHERE r.frame.id = ? AND r.verified = true AND r.frameRegionType = ?";
		Collection<FrameRegion> regions = getHibernateTemplate().find(hql, new Object[] {frame.getId(), frameRegionType});
		if (CollectionUtils.isEmpty(regions)) {
			return null;
		}
		return regions.iterator().next();
	}

}
